package com.universityJob.common.utils;

import com.alibaba.fastjson.JSON;
import jxl.SheetSettings;
import jxl.write.*;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.apache.commons.collections.MapUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;


@Component
public class ExportExcel<T extends Map> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public static String nvll(Object o){
        if(o==null) {
            return "";
        } else {
            return o.toString();
        }
    }
    private int exportToExcel(HttpServletResponse response,
                              List<Map> objData, String sheetName,
                              List<Map> columns, File file) {
        Map titles = new LinkedHashMap();
        if (!file.isFile()) {
            try {
                boolean newFile = file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        int flag = 0;
        //声明工作簿jxl.write.WritableWorkbook
        WritableWorkbook wwb;
        try {
            //根据传进来的file对象创建可写入的Excel工作薄
            OutputStream os = new FileOutputStream(file);

            wwb = jxl.Workbook.createWorkbook(os);

            /*
             * 创建一个工作表、sheetName为工作表的名称、"0"为第一个工作表
             * 打开Excel的时候会看到左下角默认有3个sheet、"sheet1、sheet2、sheet3"这样
             * 代码中的"0"就是sheet1、其它的一一对应。
             * createSheet(sheetName, 0)一个是工作表的名称，另一个是工作表在工作薄中的位置
             */
            WritableSheet ws = wwb.createSheet(sheetName, 0);
            SheetSettings ss = ws.getSettings();
            ss.setVerticalFreeze(1);//冻结表头
            WritableFont font1 = new WritableFont(WritableFont.createFont("微软雅黑"), 10, WritableFont.BOLD);
            WritableCellFormat wcf = new WritableCellFormat(font1);
            //判断一下表头数组是否有数据
            if (columns != null && columns.size() > 0) {
                int i = 0;
                //循环写入表头
                titles = columns.get(0);
                for (Object o : titles.keySet()) {
                    ws.setColumnView(i, 28);//设置列宽
                    //ps：因为要“”通用”“导出功能，所以这里循环的时候不是get("Name"),而是通过map.get(o)
                    String title = MapUtils.getString(titles, o, "");
                    ws.addCell(new Label(i, 0, title, wcf));
                    i++;
                }
            }

            //判断表中是否有数据
            if (objData != null && objData.size() > 0) {
                //循环写入表中数据
                for (int i = 0; i < objData.size(); i++) {
                    //转换成map集合{activyName:测试功能,count:2}
                    Map map = objData.get(i);
                    //循环输出map中的子集：既列值
                    int j = 0;
                    for (Object o : titles.keySet()) {
                        //ps：因为要“”通用”“导出功能，所以这里循环的时候不是get("Name"),而是通过map.get(o)
                        String content = "";
                        content = MapUtils.getString(map, (String) o, "");
                        ws.addCell(new Label(j, i + 1, content));
                        j++;
                    }
                }
            } else {
                flag = -1;
            }
            //写入Exel工作表
            wwb.write();
            //关闭Excel工作薄对象
            wwb.close();
            //关闭流
            os.flush();
            os.close();
        } catch (IllegalStateException e) {
            logger.error(e.getMessage());
        } catch (Exception ex) {
            flag = 0;
            ex.printStackTrace();
        }

        return flag;
    }
    private static List jsonTo(String feild){
        feild = "["+feild+"]";
        JSONArray jsonArray = JSONArray.fromObject(feild);
        List<Map> list = (List<Map>)JSONArray.toCollection(jsonArray, Map.class);
        return list;
    }
    public int excelInit(List<Map> result,HttpServletResponse response,Map<String, Object> params){
        try {
            String filename = (String) params.get("fileName");
            String path  = (String) params.get("path");
            String feilds = MapUtils.getString(params, "feilds");
            List list = jsonTo(feilds);
            //点击导出按钮的时候,页面上显示的标题,同时也是sheet的名称
            String uid = nvll(params.get("uid"));
            //创建临时文件夹
            File temp = new File(path + "/" + uid + "/");
            boolean bool = temp.mkdirs();
            File file = new File( path + "/" + uid + "/" + filename);
            exportToExcel(response, result, filename, list,file);
        } catch (Exception e) {
            logger.error("文件 {} 导出出错！ ",MapUtils.getString(params, "fileName","不详"));
            e.printStackTrace();
            return 0;
        }
        return 1;

    }
}
